package com.hqj.util;

import com.alibaba.fastjson.JSON;
import com.hqj.entity.Area;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {

    public static String createAreaTree(List<Area> list){
        List<Map<String,Object>> nlist = new ArrayList<>();
        for(Area a : list){
            Map<String,Object> m = new HashMap<>();
            m.put("title",a.getName());
            m.put("name",a.getName());
            m.put("id",a.getId());
            m.put("parentId",a.getParentId());
            nlist.add(m);
        }

        List<Map<String,Object>> tlist = new ArrayList<>();
        //遍历集合
        for(Map<String,Object> map : nlist){
            //顶层位置
            if("0".equals(map.get("parentId")+"")){
                map.put("children",createBranch(map,nlist));
                //添加到集合
                tlist.add(map);
            }
        }


        return JSON.toJSONString(tlist);
    }

    public static List createBranch(Map<String,Object> parentMap,List<Map<String,Object>> tlist){
        List<Map<String,Object>> childList = new ArrayList<>();
        //添加一个属性名 children
        parentMap.put("children",childList);
        //判断是否存在子区域
        for(Map<String,Object> childMap : tlist){
            //当id 与 别的数据的 parentId 存在相等 说明存在子节点 =  ==  和 equals 的区别
            if(parentMap.get("id").toString().equals(childMap.get("parentId").toString())){
                childList.add(childMap);
                //递归
                createBranch(childMap,tlist);
            }
        }

        return childList;
    }
}
